﻿using MediatR;
using Newtonsoft.Json;
using S.Common.Enums.Archives;
using S.Common.helper;
using S.Parturition.API.Application.Command;
using S.Parturition.API.Dto;
using S.Parturition.Domain;
using S.Parturition.Domain.Model;
using S.Parturition.Infrastructure.Interface;

namespace S.Parturition.API.Application.CommandHandlers
{
    public class DeleteLambHandler : IRequestHandler<DeleteLambCommand, bool>
    {

        private readonly ILambRegistrationRepository repository;

        private readonly MyDbContext dbContext;

        private readonly IHttpContextAccessor httpContextAccessor;

        private readonly IConfiguration configuration;

        public DeleteLambHandler(ILambRegistrationRepository repository, MyDbContext dbContext, IHttpContextAccessor httpContextAccessor, IConfiguration configuration)
        {
            this.repository = repository;
            this.dbContext = dbContext;
            this.httpContextAccessor = httpContextAccessor;
            this.configuration = configuration;
        }

        public async Task<bool> Handle(DeleteLambCommand request, CancellationToken cancellationToken)
        {
            //获取到网关地址
            string Gateway = configuration.GetValue<string>("Gateway");

            //获取到要删除的羔羊信息
            LambRegistrationModel lamb = repository.GetAllAsync().Result.Where(x => x.LambRegistrationId == request.LambRegistrationId).FirstOrDefault();

            using (var tran = dbContext.Database.BeginTransaction())
            {
                try
                {
                    //删除羔羊信息
                    await repository.DeleteAsync(request.LambRegistrationId);

                    #region 修改种母历史记录

                    EditBreed editBreed = new EditBreed();

                    editBreed.EarTag = lamb.MotherEar;

                    //反填种母历史记录
                    var jsonString = HttpClientHelper.PostResponseKey($"{Gateway}/bhread/api/BreedingHistoryRead/GetNewBreedingHistoryByPId", editBreed);
                    //将获取到的种母历史记录序列化
                    var response = JsonConvert.DeserializeObject<BreedingHistoryDto>(jsonString);

                    //修改种母历史记录

                    //修改分娩的羔羊数量
                    switch (lamb.BirthState)//根据羔羊出生状态判断
                    {
                        case 1:
                            response.HealthyNumber--;
                            response.TotalWeightOfHealthyLambs -= lamb.BirthWeight;
                            break;
                        case 2:
                            response.LambNumber--;
                            break;
                        case 3:
                            response.DeformityNumber--;
                            break;
                        case 4:
                            response.StillbirthsNumber--;
                            break;
                        case 5:
                            response.MummyNumber--;
                            break;
                        case 6:
                            response.FreaksNumber--;
                            break;
                    }

                    response.IsEditor = true;   //修改可编辑的状态
                    //修改种母历史记录
                    HttpClientHelper.PutDataResponse($"{Gateway}/bhset/api/BreedHistory/UpdateBreedingHistory", response);

                    #endregion

                    #region 修改档案信息

                    //反填档案信息
                    var archives = HttpClientHelper.GetResponse<SheepFileDto>($"{Gateway}/ach/api/SheepFileModel/GetSheepFilesByEarTag?EarTag=" + lamb.EarTag);

                    //删除后裔档案信息
                    var deletearchives = HttpClientHelper.DeleteResponse($"{Gateway}/achs/api/SheepFileModel/SheepFileDeletedirectPL?ids=" + archives.SheepFileId);

                    #endregion

                    #region 删除转舍信息

                    HttpClientHelper.DeleteResponse($"{Gateway}/transset/api/TransFer/DeleteSheepTransFer?EarTag=" + lamb.EarTag + "&SurrenderDate=" + lamb.BirthDate);

                    #endregion

                    #region 修改耳号使用状态

                    HttpClientHelper.PostResponse($"{Gateway}/ggyset/api/EarTag/UpdMarkStateTwo?EarTag=" + lamb.EarTag, "");

                    #endregion

                    //事物提交
                    tran.Commit();
                    return true;

                }
                catch (Exception)
                {
                    tran.Rollback();
                    return false;
                }
            }
        }


        public class EditBreed
        {
            /// <summary>
            /// 可视耳号
            /// </summary>
            public string? EarTag { get; set; }
        }


        public class SheepFileDto
        {
            /// <summary>
            /// 羊只档案Id
            /// </summary>
            public int SheepFileId { get; set; }

            /// <summary>
            /// 可视耳号
            /// </summary>
            public string EarTag { get; set; }
            /// <summary>
            /// 转舍时间
            /// </summary>
            public DateTime SurrenderDate { get; set; }
            /// <summary>
            /// 电子耳标号
            /// </summary>
            public string EITag { get; set; }
            /// <summary>
            /// 父耳号
            /// </summary>
            public string ParentEarTag { get; set; }
            /// <summary>
            /// 母耳号
            /// </summary>
            public string MotherEarTag { get; set; }
            /// <summary>
            /// 品种
            /// </summary>
            public VarietyEnum Variety { get; set; }
            public string VarietyLabel { get { return Variety.ToString(); } }

            /// <summary>
            /// 性别
            /// </summary>
            public int Sex { get; set; }
            /// <summary>
            /// 出生日期
            /// </summary>
            public DateTime BirthDate { get; set; }
            /// <summary>
            /// 入场日期
            /// </summary>
            public DateTime AdmissionDate { get; set; }
            /// <summary>
            /// 日龄
            /// </summary>
            public int Dayage { get; set; }
            /// <summary>
            /// 月龄
            /// </summary>
            public int MonthAge { get; set; }
            /// <summary>
            /// 在场状态
            /// </summary>
            public PresenceStateEnum PresenceState { get; set; }
            public string PresenceStateLabel { get { return PresenceState.ToString(); } }


            /// <summary>
            /// 生长阶段
            /// </summary>
            public GrowthStageEnum GrowthStage { get; set; }
            public string GrowthStageLabel { get { return GrowthStage.ToString(); } }

            /// <summary>
            /// 羊只类型
            /// </summary>
            public SheepType SheepType { get; set; }
            public string SheepTypeLabel { get { return SheepType.ToString(); } }

            /// <summary>
            /// 栋舍
            /// </summary>
            public string BuildingName { get; set; }
            /// <summary>
            /// 栏位
            /// </summary>
            public string ColumnName { get; set; }
            /// <summary>
            /// 繁殖状态
            /// </summary>
            public ReproductiveStateEnum ReproductiveState { get; set; }
            public string ReproductiveStateLabel { get { return ReproductiveState.ToString(); } }
            /// <summary>
            /// 繁殖状态开始日期
            /// </summary>
            public DateTime? ReproductiveStateDate { get; set; }

            /// <summary>
            /// 流转繁殖状态
            /// </summary>
            public WanderReproductiveStateEnum WanderReproductiveState { get; set; }
            public string? WanderReproductiveStateLabel { get { return WanderReproductiveState.ToString(); } }


            /// <summary>
            /// 是否妊检
            /// </summary>
            public int IsPregnancy { get; set; }
            /// <summary>
            /// 状态天数
            /// </summary>
            public int StateDays { get; set; }
            /// <summary>
            /// 生产等级
            /// </summary>
            public ProductionRankEnum ProductionRank { get; set; }
            public string ProductionRankLabel { get { return ProductionRank.ToString(); } }

            /// <summary>
            /// 销售等级
            /// </summary>
            public SalesRankEnum SalesRank { get; set; }

            public string SalesRankLabel { get { return SalesRank.ToString(); } }
            /// <summary>
            /// 基因等级
            /// </summary>
            public GeneRankEnum GeneRank { get; set; }
            public string GeneRankLabel { get { return GeneRank.ToString(); } }
            /// <summary>
            /// 出生重
            /// </summary>
            public decimal BirthWeight { get; set; }
            /// <summary>
            /// 断奶重
            /// </summary>
            public decimal WeaningWeight { get; set; }
            /// <summary>
            /// 断奶日期
            /// </summary>
            public DateTime WeaningDate { get; set; }
            /// <summary>
            /// 断奶日龄
            /// </summary>
            public int WeaningAge { get; set; }
            /// <summary>
            /// 备注
            /// </summary>
            public string Remarks { get; set; }
            /// <summary>
            /// 出生场地
            /// </summary>
            public string BirthPlace { get; set; }
            /// <summary>
            /// 出生状态
            /// </summary>
            public int BirthState { get; set; }
            /// <summary>
            /// 当前胎次
            /// </summary>
            public int CurrentParity { get; set; }
            /// <summary>
            /// 配种序号(种母配种主键Id)
            /// </summary>
            public int BreedId { get; set; }
            /// <summary>
            /// 繁殖方式
            /// </summary>
            public int ModeofReproduction { get; set; }
            /// <summary>
            /// 同胎数
            /// </summary>
            public int NumberofIdenticalBirths { get; set; }
            /// <summary>
            /// 是否售卖
            /// </summary>
            public bool IsSell { get; set; }
            /// <summary>
            /// 售卖价格
            /// </summary>
            public decimal SellingPrice { get; set; }
            /// <summary>
            /// 是否转种
            /// </summary>
            public bool IsTransplanting { get; set; }
            /// <summary>
            /// 检测状态
            /// </summary>
            public int DetectionState { get; set; }
            /// <summary>
            /// 检测是否合格
            /// </summary>
            public bool IsQualified { get; set; }
            /// <summary>
            /// 创建人
            /// </summary>
            public string CreateBy { get; set; }
            /// <summary>
            /// 创建时间
            /// </summary>
            public DateTime CreateDate { get; set; }
            /// <summary>
            /// 修改人
            /// </summary>
            public string UpdateBy { get; set; }
            /// <summary>
            /// 修改时间
            /// </summary>
            public DateTime UpdateDate { get; set; }
            /// <summary>
            /// 档案类型
            /// </summary>
            public int? FileType { get; set; }
        }


    }
}
